import axios from "axios"

// 默认路由
// axios.defaults.baseurl = 'http://www.topgun9527.top/nft/api/v1'
axios.defaults.baseurl = '/api'

// 请求头
axios.defaults.headers = {
	"content-Type": "application/json; charset=utf-8"
}

// 超时时间
axios.defaults.timeout = 10000

axios.interceptors.request.use(
	config => {
		return config
	},
	error => {
		return Promise.reject(error)
	}
)

axios.interceptors.response.use(
	response => {
		if (response.status == 200) {
			if (response.data.code === 500) {
				uni.showToast({
					title: '登录过期',
					icon: 'none'
				})
				uni.removeStorageSync('user')
				uni.navigateTo({
					url: '../login/login',
					animationType: 'pop-in',
					animationDuration: 200
				})
			}
			return Promise.resolve(response.data);
		} else {
			return Promise.reject(response);
		}
	},
	error => {
		return Promise.reject(error)
	}
)

//自己定义个适配器，用来适配uniapp的语法
axios.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle')
		var buildURL = require('axios/lib/helpers/buildURL')
		uni.request({
			method: config.method.toUpperCase(),
			url: buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};

				settle(resolve, reject, response);
			},
			fail(err) {
				console.log(err);
			}
		})
	})
}

export default {

	// post 请求
	post(url, data, headers) {
		return new Promise((resolve, reject) => {
			axios({
				method: "POST",
				url: axios.defaults.baseurl + url,
				data: data,
				headers: headers ? headers : {}
			}).then((res) => {
				resolve(res)
			}).catch((err) => {
				reject(err)
			})
		})
	},

	// get 请求
	get(url, params) {
		return new Promise((resolve, reject) => {
			axios({
				method: "GET",
				url: axios.defaults.baseurl + url,
				params: params
			}).then((res) => {
				resolve(res)
			}).catch((err) => {
				reject(err)
			})
		})
	},

	down(url, data, headers) {
		return new Promise((resolve, reject) => {
			axios({
				method: "POST",
				url: axios.defaults.baseurl + url,
				data: data,
				headers: headers ? headers : {},
				responseType: "arraybuffer"
			}).then((res) => {
				resolve(res)
			}).catch((err) => {
				reject(err)
			})
		})
	},

}
